<?php

class UserController extends Controller
{
	/**
	 * 权限验证
	 */
	public function  __construct()
	{
		if(!in_array(Core::$action[1],array('show','login','logout','reg'))){
			UserAuthHelper::authenticate();
		}
	}

	/**
	 * 用户个人首页
	 */
	public function show()
	{
		$uid	=	fetch_get('uid','int');
		if(!$uid || !($user=User::get($uid)))
		{
			$this->redirect();
		}
		$this->assign('user', $user);

		$this->display();
	}
	
	/**
	 * 用户登陆页面
	 */
	public function login()
	{
		if(!empty($_POST))
		{
			$username	=	strtolower(fetch_post('username'));
			$password	=	fetch_post('password', 'char');
			if($username && $password)
			{
				if(UserAuthHelper::doLogin($username, $password))
				{
					if(fetch_get('r')){
						header('location: '.base64_decode(fetch_get('r')));
					}
					elseif(fetch_post('referer')){
						header('location: '.fetch_post('referer'));
					}
					else{
						$this->redirect();
					}
				}
				else
				{
					Show::warning('登陆失败，用户名或密码错误', 'SELF');
				}
			}
			else
			{
				Show::warning('输入用户名和密码', 'SELF');
			}
		}

		$this->display();
	}

	public function logout()
	{
		UserAuthHelper::doLogout();

		if(fetch_get('r')){
			header('location: '.base64_decode(fetch_get('r')));
		}
		elseif(!empty($_SERVER['HTTP_REFERER'])){
			header('location: '.$_SERVER['HTTP_REFERER']);
		}
		else{
			$this->redirect();
		}
	}

	/**
	 * 用户注册页面
	 *
	 */
	public function reg()
	{
		if(!empty($_POST))
		{
			$username	=	strtolower(fetch_post('username'));
			$password	=	fetch_post('password', 'char');
			$passwd2	=	fetch_post('password2', 'char');
			$nickname	=	fetch_post('name');
//			$vacode		=	strtolower(fetch_post('va'));

			if(!$username)
			{
				Show::warning('请输入登陆用户名');
			}
			elseif(!StringHelper::email($username))
			{
				Show::warning('请输入正确有效的邮箱做为用户名');
			}
			if(!$password || $password!=$passwd2)
			{
				Show::warning('您的登陆密码不能留空，且两次密码输入要一致');
			}
//			if(!$vacode)
//			{
//				Show::warning('请输入图片上的验证码');
//			}
//			elseif(0 && $vacode==$_SESSION['VACODE'])
//			{
//				Show::warning('验证码输入有误');
//			}

			$uid	=	User::add(array(
							'username'	=>	$username,
							'password'	=>	UserAuthHelper::encrypt($password),
							'email'		=>	$username,
							'name'		=>	$nickname,
							'regtime'	=>	time(),
						));
			if($uid>0)
			{
				Show::notice('恭喜注册成功', 'user-login/u/'.$username, 3);
			}
			else
			{
				Show::warning('注册失败，请稍候再试', WEB_ROOT, 3);
			}
		}

		$this->display();
	}

	public function changepass()
	{
		if(isset($_POST['submit2']))
		{
			$r	=	self::changePasswd(fetch_post('password1', 'char'), fetch_post('password2', 'char'));
			switch($r)
			{
			case  0:	$message	=	"密码修改成功";	break;
			case -1:	$message	=	"新密码不能为空";	break;
			case -2:	$message	=	"原始密码错误";	break;
			case -3:	$message	=	"修改操作失败";	break;
			case -4:	$message	=	"两次密码输入不一致";	break;
			}
			$this->assign('errmsg',	$message);
		}

		$this->display();
	}

	public function info()
	{
		if(UserAuthHelper::isLogin())
			$this->display();
		else
			$this->redirect();
	}

	/**
	 * listbook
	 */
	public function listbook()
	{
		$page	=	fetch_get('p','int');
		$list	=	Book::getList($page);
		
		$this->assign('list', $list);
		$this->display();
	}

	/**
	 * 查看指定book信息
	 */
	public function book()
	{
		$bookid	=	fetch_get('id','int');
		if(!$bookid)
		{
			Show::warning("无此书籍信息");
		}
		$book	=	Book::getBook($bookid);
		if(!$book)
		{
			Show::go400("无此书籍信息");
		}

		$this->assign('book', $book);
		$this->display();
	}

	public function addbook()
	{
		import('#/helper/String.php');
		
		if(!empty($_POST))
		{
			//todo: 可支持上传zip或tar格式的文本
			if(empty($_FILES['book']) || $_FILES['book']['error'] || ('text/plain'!=$_FILES['book']['type']) )
			{
				Show::warning("请上传正确的文本书籍，并检查上传文件大小<".ini_get('upload_max_filesize'), 'user-addbook');
			}
			
			$cont	=	StringHelper::encode(file_get_contents($_FILES['book']['tmp_name']));
			$path	=	Book::storeBook($cont);
			$desc	=	fetch_post('desc') ? fetch_post('desc') : mb_substr($cont, 0, 180, 'UTF-8');
			
			$bookid	=	Book::addBook(array(
				'title'		=>	fetch_post('title'),
				'user_id'	=>	UserAuthHelper::uid(),
				'desc'		=>	$desc,
				'path'		=>	$path,
				'addtime'	=>	time(),
				'length'	=>	strlen($cont),
			));
			
			$this->redirect('user-book/id/'.$bookid);
		}
		
		$this->display();
	}
	
	/**
	 * 编辑书籍信息
	 */
	public function editbook()
	{
		if(!UserAuthHelper::isAdmin()){
			Show::warning("目前只有管理员能编辑书籍信息");
		}

		$bookid	=	fetch_get('id','int');
		if(!$bookid)
		{
			Show::warning("无此书籍信息");
		}
		$book	=	Book::getBook($bookid);
		if(!$book)
		{
			Show::go400("无此书籍信息");
		}
		
		if(!empty($_POST))
		{
			Book::editBook($bookid, array(
				'title'		=>	fetch_post('title'),
				'desc'		=>	fetch_post('desc'),
			));
			$this->redirect('user-book/id/'.$bookid);
		}
		
		$this->assign('book', $book);
		$this->display();
	}

	/**
	 * 删除书籍信息
	 */
	public function dropbook()
	{
		if(!UserAuthHelper::isAdmin()){
			Show::warning("目前只有管理员能删除书籍");
		}

		$bookid	=	fetch_get('id','int');
		if(!$bookid){
			Show::warning("无此书籍信息");
		}

		if(Book::dropBook($bookid)){
			Show::notice('删除成功');
		}
		else{
			Show::warning('删除失败，请确认书籍信息正确');
		}
	}

	//-----------------------------PRIVATE METHOD-------------------------------

	/** 修改个人密码   */
	private static function changePasswd($passwd1, $passwd2, $uid=0)
	{
		if(empty($passwd1))
		{
			return -1;
		}
		$user	=	Adminuser::get($uid ? $uid : $_SESSION['USER']['id']);
//		if(self::encrypt($oldpasswd) != $user['password'])
//		{
//			return -2;
//		}
		if($passwd1!=$passwd2)
		{
			return -4;
		}
		if(!Adminuser::changePasswd($user['id'], UserAuthHelper::encrypt($passwd1)))
		{
			return -3;
		}
		return 0;
	}

}

?>